package com.cloud.goods.controller;

import com.cloud.goods.service.ITbItemService;
import com.cloud.mall.goods.TbItem;
import com.cloud.mall.goods.dto.ItemStockDto;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 商品表 前端控制器 GUN
 * </p>
 *
 * @author jobob
 * @since 2021-07-05
 */
@Slf4j
@RestController
@RequestMapping("/goods/tb-item")
public class TbItemController {
    @Autowired
    private ITbItemService iTbItemService;

    @RequestMapping("/getById")
    public TbItem getById(@RequestParam("id") Long id) {
        if (null == id) {
            return null;
        }
        return iTbItemService.getById(id);
    }

    @RequestMapping("/save")
    public boolean save(@RequestBody TbItem tbItem) {
        if (null == tbItem) {
            throw new RuntimeException("数据为空，插入失败");
        }
        return iTbItemService.save(tbItem);
    }

    @RequestMapping("/delete")
    public boolean delete(@RequestParam("id") Long id) {
        if (null == id) {
          throw new RuntimeException("数据为空，删除失败");
        }
        return iTbItemService.removeById(id);
    }

    @RequestMapping("/update")
    public boolean update(@RequestBody TbItem tbItem) {
        if (null == tbItem) {
           throw new RuntimeException("数据为空，修改失败");
        }
        return iTbItemService.updateById(tbItem);
    }

    @RequestMapping("/listByPage")
    public PageInfo<TbItem> listByPage(@RequestBody TbItem tbItem) {
        int pageNum = 1;
        int pageSize = 10;
        if (null != tbItem && tbItem.getPageNum() != null) {
            pageNum = tbItem.getPageNum();
        }
        if (null != tbItem && tbItem.getPageSize() != null) {
           pageSize = tbItem.getPageSize();
        }
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<TbItem>(iTbItemService.list());
    }

    @RequestMapping("/listAll")
    public List<TbItem> listAll() {
        return iTbItemService.list();
    }

    //    扣减库存
    @RequestMapping("/decreaseGoodsAmount")
    public boolean decreaseGoodsAmount(@RequestBody List<ItemStockDto> itemStockDtos) {
        log.info("decreaseGoodsAmount begin");
        return iTbItemService.decreaseGoodsAmount(itemStockDtos);
    }

    //    根据ID查询商品信息
    @RequestMapping("/listByIds")
    public List<TbItem> listByIds(@RequestBody List<Long> ids) {
        log.info("decreaseGoodsAmount listByIds");
        return iTbItemService.listByIds(ids);
    }
}
